package com.leexuan.ordersystem.actions;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.leexuan.ordersystem.beans.Invoice;
import com.leexuan.ordersystem.beans.Order;
import com.leexuan.ordersystem.db.InvoiceDB;
import com.leexuan.ordersystem.db.OrderDB;

public class AddInvoice2Action extends Action {

	public AddInvoice2Action() {
		super();
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		int oid = Integer.parseInt(request.getParameter("oid"));

		OrderDB odb = new OrderDB();
		InvoiceDB idb = new InvoiceDB();

		try {
			idb.getConnection();

			odb.getConnection();

			Order order = odb.getOrder(oid);

			Invoice in = new Invoice();

			in.setOid(order.getOid());
			in.setRemain(order.getSum());
			in.setTotal(order.getSum());

			Date date = new Date();

			SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");

			in.setDate(bartDateFormat.format(date));

			idb.addInvoice(in);

			return mapping.findForward("success");

		} catch (Exception e) {

			return (new ActionForward(mapping.getInput()));
		} finally {
			try {
				odb.closeConnection();
				idb.closeConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
